package com.study.jvm.test.classloader;

import java.io.*;

public class MyClassLoader extends ClassLoader {

    /**
     * 重写findClass方法
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
//        throw new ClassNotFoundException(name);
        // 文件
        File file = new File("D:/Study/",name.replace(".","/").concat(".class"));

        try {
            // 文件输入流
            FileInputStream inputStream = new FileInputStream(file);
            // 字节输出流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            // 将文件以字符形式(二进制)写入
            int b = 0;
            while ((b=inputStream.read()) != 0){
                byteArrayOutputStream.write(b);
            }

            byte[] bytes = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            inputStream.close();
            // 将字节信息转化为class对象
            return  defineClass(name,bytes,0, bytes.length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.findClass(name);

    }

}
